package cn.hp.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import cn.hp.domain.User;
import cn.hp.service.PermissionService;
import cn.hp.service.RoleService;
import cn.hp.service.UserService;
import cn.hp.utils.ActiveUser;

public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	
	@Override
	public String getName() {
		return this.getClass().getName();
	}
	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//获得用户名进行认证
		String username = token.getPrincipal().toString();
		//根据用户名查询用户是否存在
		User user=userService.findUserByUsername(username);
		if(user !=null){
			//根据用户id查询用户拥有哪些角色
			List<String> roleList=roleService.findRolesByUserId(user.getUserid());
			//根据用户id查询用户拥有哪些权限
			List<String> permissionList=permissionService.findPermissionsByUserId(user.getUserid());
			//封装到ActiveUser进行返回
			ActiveUser activeUser=new ActiveUser(user, roleList, permissionList);
			//盐值:用户名作为盐
			ByteSource credentialsSalt=ByteSource.Util.bytes(user.getUsername());
			SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(activeUser,user.getUserpwd(), credentialsSalt, getName());
			return info;
		}
		return null;
	}
	
	
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
		//获得用户有哪些角色
		List<String> roleList = activeUser.getRoleList();
		System.out.println(roleList);
		if(roleList !=null && roleList.size()>0){
			info.addRoles(roleList);
		}
		//获得用户有哪些权限
		List<String> permissionList = activeUser.getPermissionList();
		System.out.println(permissionList);
		if(permissionList !=null && permissionList.size()>0){
			info.addStringPermissions(permissionList);
		}
		return info;
	}

}
